package com.huizhonglm.diap.core.alipay;

import com.huizhonglm.diap.api.model.user.OrderInfo;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.spec.PKCS8EncodedKeySpec;

public class SignUtils {
	private static final String PARTNER = "2088321043585148";

	private static final String SELLER = "fanjiankuan@126.com";
	// 商户私钥，pkcs8格式
	private static final String RSA_PRIVATE =
			"MIICeQIBADANBgkqhkiG9w0BAQEFAASCAmMwggJfAgEAAoGBANI4BvcQ6Om8jRUX" +
			"wp+ayU+eT07PLgh75bPIkSfMAckB8BOg1dkbYy+k9mWxpzyM9VFiwA2OanPWfQb5" +
			"uEaBpZHdIhC1VtuBI9126S7p58DSfS0BMNY+zouTFFUycC+aEJ+4sjNOETm+i/Sn" +
			"GA9HxowK23gJ7M1SpqvOMJPTdIFHAgMBAAECgYEAmS1uFdVigf58JuR7UmUtTzCh" +
			"xWE9v7zX8Zqx+neyzU72KrdFW7+TFIJ1cEB1BbAIiVcVbktZ0jJ2RADuf6G0jDNr" +
			"4J+wjzltKt6PmzZqf0IuR0g2IfhJhSw8qg/+BBl94BVy5Qfe2Vpw2+LK7IDgWRwj" +
			"Ets5BztfqZoWdJUuSbECQQD80DeaWRfKKXDjp/sCjlDzKQcyssIEPa5kfQsUl/Cz" +
			"DHmch7egM0EOuMekqBNj5yinA6bBXCiGnPT6zJam7X3zAkEA1N5dhQsLL2P80Iaz" +
			"k5q5ADmgEsKZkj0/v0IzgE0GabD+ikhMH+ycUC0eITm/P+8+3p2CD1KrnSMFzXCV" +
			"UMtAXQJBANJ1D2SpODmuJ/EMnNPy34adKAXXc9YN9whmY/v/xHt5Lh/Vh1KQeF8m" +
			"CeSTmpi3DUuDqaUb8AynyvShreRGnmsCQQCWawMeji07MaZmG6ktdjmgJRgt6YDn" +
			"S4yOM9N8p/EOIlnbkTbpoCLcrOULiWjRXtfIKvjKpxpJkYP6JcH9M4KpAkEAq9y4" +
			"OqBZW3uboG78sewzZSSQwlafYtHuptUTQUTtzyjxiMWxH52ZCQeQabEYxgEb0Xjk" +
			"scHJWyS0MapLqHkM6g==";

	private static final String ALGORITHM = "RSA";

	private static final String SIGN_ALGORITHMS = "SHA1WithRSA";

	private static final String DEFAULT_CHARSET = "UTF-8";

	public static String getOrderInfo(OrderInfo order){
		try {
//			String orderInfo = getOrderInfo(order.getOrderId(), order.getName(), order.getRemark(), order.getTotalPrice());
			String orderInfo = getOrderInfo(order.getOrderId(), "李晓龙的测试订单", "李晓龙的测试订单描述", order.getTotalPrice());
			/**
			 * 特别注意，这里的签名逻辑需要放在服务端，切勿将私钥泄露在代码中！
			 */
			String sign = sign(orderInfo, RSA_PRIVATE);
			/**
			 * 仅需对sign 做URL编码
			 */
			sign = URLEncoder.encode(sign, "UTF-8");
			/**
			 * 完整的符合支付宝参数规范的订单信息
			 */
			return orderInfo + "&sign=\"" + sign + "\"&" + getSignType();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return null;
		}
	}

	private static String getOrderInfo(String orderNo, String subject, String body, Double price) {
		// 签约合作者身份ID
		String orderInfo = "partner=" + "\"" + PARTNER + "\"";
		// 签约卖家支付宝账号
		orderInfo += "&seller_id=" + "\"" + SELLER + "\"";
		// 商户网站唯一订单号
		orderInfo += "&out_trade_no=" + "\"" + orderNo + "\"";
		// 商品名称
		orderInfo += "&subject=" + "\"" + subject + "\"";
		// 商品详情
		orderInfo += "&body=" + "\"" + body + "\"";
		// 商品金额
		orderInfo += "&total_fee=" + "\"" + price + "\"";
		// 服务器异步通知页面路径
		orderInfo += "&notify_url=\"http://www.huizhonglm.com/mobile/alipay/notify\"";
		// 服务接口名称， 固定值
		orderInfo += "&service=\"mobile.securitypay.pay\"";
		// 支付类型， 固定值
		orderInfo += "&payment_type=\"1\"";
		// 参数编码， 固定值
		orderInfo += "&_input_charset=\"utf-8\"";
		// 设置未付款交易的超时时间
		// 默认30分钟，一旦超时，该笔交易就会自动被关闭。
		// 取值范围：1m～15d。
		// m-分钟，h-小时，d-天，1c-当天（无论交易何时创建，都在0点关闭）。
		// 该参数数值不接受小数点，如1.5h，可转换为90m。
		orderInfo += "&it_b_pay=\"30m\"";
		// extern_token为经过快登授权获取到的alipay_open_id,带上此参数用户将使用授权的账户进行支付
		// orderInfo += "&extern_token=" + "\"" + extern_token + "\"";
		// 支付宝处理完请求后，当前页面跳转到商户指定页面的路径，可空
		orderInfo += "&return_url=\"http://www.huizhonglm.com/mobile/alipay/returnUrl\"";
		// 调用银行卡支付，需配置此参数，参与签名， 固定值 （需要签约《无线银行卡快捷支付》才能使用）
		// orderInfo += "&paymethod=\"expressGateway\"";
		return orderInfo;
	}

	/**
	 * get the sign type we use. 获取签名方式
	 *
	 */
	private static String getSignType() {
		return "sign_type=\"RSA\"";
	}

	public static String sign(String content, String privateKey) {
		try {
			PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(Base64.decode(privateKey));
			KeyFactory keyf = KeyFactory.getInstance(ALGORITHM);
			PrivateKey priKey = keyf.generatePrivate(priPKCS8);
			java.security.Signature signature = java.security.Signature.getInstance(SIGN_ALGORITHMS);
			signature.initSign(priKey);
			signature.update(content.getBytes(DEFAULT_CHARSET));
			byte[] signed = signature.sign();
			return Base64.encode(signed);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

}
